import { defineStore } from "pinia"
import { login as loginApi, register as registerApi,LoginData,RegisterData, getRoles, getUserInfo, logout } from "../api/loginApi"
import { HTTP_STATUS } from "../api/request"
export interface UserInfo {
  loginId: string,
  nickname: string,
  email: string,
  phone: string
}

export const useLoginStore = defineStore("login", {
  persist: {
    key: "userToken"
  },
  state: () => ({
    token: null as string | null,
    userInfo: null as UserInfo | null,
    roles: [] as string[],
    perms: [] as string[]
  }),
  getters: {
    
  },
  actions: {
    //是否持有token
    isAuthenticated(): boolean {
      return this.token != null
    },
    //设置验证token
    setToken(tokenData: string) {
      this.token = tokenData
    },
    //移除验证token(登出)
    removeToken() {
      this.token = null
      this.userInfo = null
      this.roles = []
      this.perms = []
    },
    //发送登录请求
    async requestLogin(userData: LoginData) {
      let res : any = await loginApi(userData)
      
      const status = res.status
      if (status === HTTP_STATUS.SUCCESS) {
        let userInfoRes = await getUserInfo()
        this.userInfo = userInfoRes.data
        this.perms = userInfoRes.data.permissions
        this.roles = (await getRoles()).data
      }
      return res
    },
    //发送注册请求
    async requestRegister(userData: RegisterData) {
      let res: any = await registerApi(userData)
      return res
    },

    //退出登录
    async requestLogout() {
      if (!this.isAuthenticated()) {
        return
      }
      const res : any = await logout()
      if (res.status === HTTP_STATUS.SUCCESS) {
        this.removeToken()
      }
      return res
    }
  }
})